/**
 * 缓存封装
 */
import os from '../os.js';

/**
 * 取值
 */
const get = function(key, sync = true) {
    try {
		if(sync){
			return os.getStorageSync(key);
		}else{
			let data = '';
			os.getStorage({
				key:key,
				success: function (res) {
					data = res.data;
				}
			});
			return data;
		}
    } catch (e) {
        return false;
    }
}

/**
 * 赋值
 */
const set = function(key, value, sync = true) {
    try {
        if (sync) {
            return os.setStorageSync(key, value);
        } else {
            os.setStorage({
                key: key,
                data: value
            });
        }
    } catch (e) {
        return false;
    }
}

/**
 * 移除
 */
const del = function(key, sync = true){
    try {
        if (sync) {
            return os.removeStorageSync(key);
        } else {
            os.removeStorage({
                key: key
            });
        }
    } catch (e) {
        return false;
    }
}

/**
 * 清空
 */
const clear = function(sync = true){
    try {
        if (sync) {
            return os.clearStorageSync();
        } else {
            os.clearStorage();
        }
    } catch (e) {
        return false;
    }
}

/**
 * 获取用户信息
 */
const getUserInfo = function(){
    try {
        let res = get('userInfo');
        if(res){
            return JSON.parse(res);
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 更新用户信息
 */
const updateUserInfo = function(data){
    return set('userInfo', JSON.stringify(data));
}

/**
 * 获取搜索历史
 */
const getSearchHistory = function(){
    try {
        let res = get('search_history');
        if(res){
            return JSON.parse(res);
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 清除搜索历史
 */
const delSearchHistory = function(){
    return del('search_history');
}

/**
 * 更新搜索历史
 */
const updateSearchHistory = function(data){
    return set('search_history', JSON.stringify(data));
}

/**
 * 获取渠道配置
 */
const getOamarkConf = function(){
    try {
        let res = get('oamark_config');
        if(res){
            return JSON.parse(res);
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 清除渠道配置
 */
const delOamarkConf = function(){
    return del('oamark_config');
}

/**
 * 更新渠道配置
 */
const updateOamarkConf = function(data){
    return set('oamark_config', JSON.stringify(data));
}

/**
 * 获取当前短剧已解锁剧集
 */
const getUnlockEpisodes = function(playletId){
    try {
        let res = get('unlock_episodes_' + playletId);
        if(res){
            return JSON.parse(res);
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 更新当前短剧解锁剧集
 */
const updateUnlockEpisodes = function(playletId, data){
    return set('unlock_episodes_' + playletId, JSON.stringify(data));
}

/**
 * 保存未支付订单
 */
const saveNoPayOrder = function(data){
    return set('no_pay_order', data);
}

/**
 * 获取未支付订单
 */
const getNoPayOrder = function(){
    try {
        let res = get('no_pay_order');
        if(res){
            return res;
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 清除未支付订单
 */
const delNoPayOrder = function(){
    return del('no_pay_order');
}

/**
 * 保存环境配置
 */
const saveEnvConf = function(data){
    return set('env_config', data);
}

/**
 * 获取环境配置
 */
const getEnvConf = function(){
    try {
        let res = get('env_config');
        if(res){
            return res;
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * 删除环境配置
 */
const delEnvConf = function(){
    return del('env_config');
}

/**
 * 保存观看历史
 */
const addSeenHistoryLogs = function(data){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    data.update_time = Math.floor(Date.now() / 1000);
    if(historyArr.length === 0){
        historyArr.push(data);
    } else {
        // 将存在的剧集从历史记录中删除
        historyArr = historyArr.filter(item => item.playlet_id !== data.playlet_id);
        // 将新的剧集添加到历史记录中
        historyArr.unshift(data);
        // 只保留最近的一个月的数据
        historyArr = historyArr.filter(item => {
            const now = data.update_time;
            const threeMonthAgo = now - 30 * 24 * 60 * 60;
            return item.update_time > threeMonthAgo;
        });
    }
    return set(key, JSON.stringify(historyArr));
}

/**
 * 分页获取观看历史
 */
const getSeenHistoryLogs = function(page, pageSize){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    if(historyArr.length === 0){
        return {
            count: 0,
            current_page: 1,
            total_page: 1,
            list: []
        };
    } else {
        return {
            count: historyArr.length,
            current_page: page,
            total_page: Math.ceil(historyArr.length / pageSize),
            list: historyArr.slice((page - 1) * pageSize, page * pageSize)
        };
    }
}

/**
 * 获取最新一条观看历史
 */
const getSeenLastData = function(){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    if(historyArr.length > 0){
        return historyArr[0];
    }
    return false;
}

/**
 * 获取某剧观看历史最后剧集
 */
const getSeenLastNum = function(playletId, defNum = 1){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    if(historyArr.length > 0){
        const index = historyArr.findIndex(obj => obj.playlet_id === playletId);
        if (index !== -1) {
            return historyArr[index].last_num;
        }
    }
    return defNum;
}

/**
 * 批量更新观看历史
 */
const updateSeenHistoryLogs = function(playletId, data){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    if(historyArr.length === 0){
        return false;
    } else {
        historyArr = historyArr.map(item => {
            if(Array.isArray(playletId)){
                if(playletId.includes(item.playlet_id)){
                    Object.assign(item, data);
                }
            } else {
                if(item.playlet_id === playletId){
                    Object.assign(item, data);
                }
            }
            return item;
        });
        return set(key, JSON.stringify(historyArr));
    }
}

/**
 * 批量删除观看历史
 */
const delSeenHistoryLogs = function(playletIds){
    const key = 'seen_history_logs';
    const history = get(key) || '[]';
    let historyArr = JSON.parse(history);
    if(historyArr.length === 0){
        return false;
    } else {
        historyArr = historyArr.filter(item => !playletIds.includes(item.playlet_id));
        return set(key, JSON.stringify(historyArr));
    }
}

/**
 * 保存观看历史
 */
const saveLastSeenHistory = function(data = {}){
    const key = 'last_seen_history_logs';
    return set(key, JSON.stringify(data));
}

/**
 * 获取最后观看历史
 */
const getLastSeenHistory = function(){
    const key = 'last_seen_history_logs';
    const history = get(key) || '{}';
    let historyObj = JSON.parse(history);
    if(Object.keys(historyObj).length === 0){
        return false;
    } else {
        return historyObj;
    }
}

/**
 * 清除最后观看历史
 */
const clearLastSeenHistory = function(){
    return del('last_seen_history_logs');
}

module.exports = {
    get,
    set,
    del,
    clear,
    getUserInfo,
    updateUserInfo,
    getSearchHistory,
    delSearchHistory,
    updateSearchHistory,
    updateUnlockEpisodes,
    getUnlockEpisodes,
    getOamarkConf,
    delOamarkConf,
    updateOamarkConf,
    saveNoPayOrder,
    getNoPayOrder,
    delNoPayOrder,
    saveEnvConf,
    getEnvConf,
    delEnvConf,
    addSeenHistoryLogs,
    getSeenHistoryLogs,
    updateSeenHistoryLogs,
    delSeenHistoryLogs,
    getSeenLastNum,
    getSeenLastData,
    saveLastSeenHistory,
    getLastSeenHistory,
    clearLastSeenHistory
}
